package com.presto.directo.net

import com.presto.directo.entity.UserEntity
import com.presto.directo.utils.SPUtil
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object CipherUtil {
    private val hexDigits = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')

    fun getCipher(): String {
        val user = SPUtil.getObject<UserEntity>("user")
        if (user?.signKeyToken.isNullOrBlank()) {
            return SignUtil.key.split(";")[0]
        } else {
            return user!!.signKeyToken
        }
    }

    /**
     * MD5加密摘要计算
     *
     * @param originstr
     * @return string
     */
    @JvmStatic
    fun ecodeByMD5(originstr: String?): String? {
        var result: String? = null
        if (originstr != null) {
            try {
                val md = MessageDigest.getInstance("MD5")
                val source = originstr.toByteArray(charset("utf-8"))
                md.update(source)
                val tmp = md.digest()
                val str = CharArray(32)
                var i = 0
                var j = 0
                while (i < 16) {
                    val b = tmp[i]
                    str[j++] = hexDigits[b.toInt() ushr 4 and 0xf]
                    str[j++] = hexDigits[b.toInt() and 0xf]
                    i++
                }
                result = String(str) // 结果转换成字符串用于返回
            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
            } catch (e: UnsupportedEncodingException) {
                e.printStackTrace()
            }
        }
        return result
    }
}